package net.emsquared.gamedev.maps;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g2d.tiled.TileAtlas;
import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;

/**
 * Code is not copyrighted...I don't think.
 *
 * @author Matt Meza (mmeza84@gmail.com)
 */

public class WorldMap
{
   private TileAtlas atlas;
   private TiledMap map;
   private TileMapRenderer mapRenderer;

   public WorldMap(FileHandle mapHandle, FileHandle atlasHandle)
   {
      map = TiledLoader.createMap(mapHandle);
      atlas = new TileAtlas(map, atlasHandle);
      mapRenderer = new TileMapRenderer(map, atlas, 4, 4);
   }

   public float getMapWidth_Pix()
   {
      return map.width * map.tileWidth;
   }

   public float getMapHeight_Pix()
   {
      return map.height * map.tileHeight;
   }

   public float getMapWidth_Tiles()
   {
      return map.width;
   }

   public float getMapHeight_Tiles()
   {
      return map.height;
   }

   public void renderMap(OrthographicCamera aCamera)
   {
      mapRenderer.render(aCamera);
   }

   public TextureRegion getRegionForWorldCoords(float x, float y)
   {
      int indexForX = mapRenderer.getCol((int) x);
      int indexForY = mapRenderer.getCol((int) y);
      int index = map.layers.get(0).tiles[indexForX][indexForY];

      return atlas.getRegion(index);
   }

   public MapCoordinates convertToMapCoordinates(int tileIndexX, int tileIndexY)
   {
      return new MapCoordinates(((tileIndexX + 1) * map.tileWidth) - (map.tileWidth / 2),
              ((tileIndexY + 1) * map.tileHeight) - (map.tileHeight/ 2));
   }
}
